package com.example.heimashop.view.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;

import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.example.heimashop.base.BaseActivity;
import com.example.heimashop.databinding.ActivitySearchBinding;
import com.example.heimashop.utils.ToastUtils;
import com.example.heimashop.view.adapter.ProductAdapter;
import com.example.heimashop.viewmodel.ProductViewModel;

/**
 * 搜索页面
 * 页面7: SearchActivity - 搜索页面
 */
public class SearchActivity extends BaseActivity<ActivitySearchBinding> {

    private ProductViewModel viewModel;
    private ProductAdapter productAdapter;

    @Override
    protected ActivitySearchBinding getViewBinding() {
        return ActivitySearchBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        viewModel = new ViewModelProvider(this).get(ProductViewModel.class);

        productAdapter = new ProductAdapter();
        binding.rvSearchResult.setLayoutManager(new GridLayoutManager(this, 2));
        binding.rvSearchResult.setAdapter(productAdapter);
    }

    @Override
    protected void initData() {
        viewModel.productsLiveData.observe(this, products -> {
            if (products != null) {
                productAdapter.setData(products);
            }
        });

        viewModel.errorLiveData.observe(this, error -> {
            if (error != null) {
                ToastUtils.showShort(this, error);
            }
        });
    }

    @Override
    protected void initListener() {
        // 取消按钮
        binding.tvCancel.setOnClickListener(v -> finish());

        // 搜索框回车
        binding.etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                performSearch();
                return true;
            }
            return false;
        });

        // 商品点击
        productAdapter.setOnItemClickListener(product -> {
            Intent intent = new Intent(this, ProductDetailActivity.class);
            intent.putExtra("productId", product.getGoodsId());
            startActivity(intent);
        });
    }

    private void performSearch() {
        String query = binding.etSearch.getText().toString().trim();
        if (TextUtils.isEmpty(query)) {
            ToastUtils.showShort(this, "请输入搜索关键字");
            return;
        }
        viewModel.searchProducts(query, 1);
    }
}
